import { useRef } from "react";
import { Avatar, Modal, Dropdown, message } from "antd";
import { useNavigate } from "react-router-dom";
import { HOME_URL } from "@/config/config";
import { connect } from "react-redux";
import PasswordModal from "./PasswordModal";
import InfoModal from "./InfoModal";
import defaultAvatar from "@/assets/images/avatar.png";
import { useTranslation } from "react-i18next";
import { logoutAction, refreshMenuAction } from "@/redux/modules/permission/asyncAction";
import Icon from "@/components/Icon";
// import { useAliveController } from "react-activation";

const AvatarIcon = (props: any) => {
	const { t } = useTranslation();
	const { userInfo } = props;
	const navigate = useNavigate();
	// const { clear } = useAliveController();

	interface ModalProps {
		showModal: (params: { name: number }) => void;
	}
	const passRef = useRef<ModalProps>(null);
	const infoRef = useRef<ModalProps>(null);

	// 退出登录
	const logout = () => {
		Modal.confirm({
			title: t("logout.reminder"),
			icon: <Icon icon="ant-design:exclamation-circle-filled" />,
			content: t("logout.youWantLogOut"),
			okText: "Yes",
			cancelText: "No",
			onOk: async () => {
				await logoutAction();
				message.success(t("logout.toastLogoutSuccess"));
				// clear();
				navigate("/login");
			}
		});
	};

	const refreshMenu = async () => {
		await refreshMenuAction();
		navigate(HOME_URL);
	};

	const items = [
		{
			key: "1",
			label: <span className="dropdown-item">Home Page</span>,
			onClick: () => navigate(HOME_URL)
		},
		{
			key: "2",
			type: "divider"
		},
		{
			key: "3",
			label: <span className="dropdown-item">Refresh Menu</span>,
			onClick: refreshMenu
		},
		{
			key: "4",
			type: "divider"
		},
		{
			key: "5",
			label: <span className="dropdown-item">Quit System</span>,
			onClick: logout
		}
	];

	return (
		<>
			<Dropdown menu={{ items }} placement="bottom" arrow trigger={["click"]}>
				<Avatar size="large" src={userInfo?.user?.avatar ?? defaultAvatar} />
			</Dropdown>
			<InfoModal innerRef={infoRef}></InfoModal>
			<PasswordModal innerRef={passRef}></PasswordModal>
		</>
	);
};

const mapStateToProps = (state: any) => state.user;
export default connect(mapStateToProps, null)(AvatarIcon);
